<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'

import {
  useMessage,
  NButton,
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NPopconfirm,
  NTreeSelect,
  NTag,
  NSwitch,
  NFlex,
  NAvatar,
  NSelect,
  NImage,
  NDataTable,
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import TheIcon from '@/components/icon/TheIcon.vue'
import { getToken } from '@/utils'
import { renderIcon } from '@/utils'
import { useCRUD } from '@/composables'
// import { loginTypeMap, loginTypeOptions } from '@/constant/data'
import api from '@/api'
import { router } from '@/router'
import default_image from '@/assets/images/mz.jpg'

defineOptions({ name: '购物车' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE

const {
  modalVisible,
  modalTitle,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '购物车',
  initForm: {},
  doCreate: api.createOrdersCar,
  doUpdate: api.updateOrdersCar,
  doDelete: api.deleteOrdersCar,
  refresh: () => $table.value?.handlerefresh(),
})
const isDisabled = ref(false)
const data = reactive({
  attributeOption: [
    {
      id: 1,
      name: '描述模板',
    },
    {
      id: 2,
      name: '规格模板',
    },
  ],
  state_option:[],
  uploadAction: base_path + 'api/goods/brand/file',
  token: getToken(),
  onLevelData:[]
})


onMounted(() => {
  api.getOrdersType().then((res) => (data.state_option = res.data))
  $table.value?.handleSearch()
})

const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 100,
    align: 'center',
    ellipsis: { tooltip: true },
  },

  {
    title: '用户',
    key: 'user_name',
    width: 100,
    align: 'center',
    ellipsis: { tooltip: true },
    fixed: 'left',
  },
     {
        title: '封面图',
        key: 'goods_cover',
        width: 40,
        align: 'center',
        ellipsis: { tooltip: true },
        render(row) {
            return h(NFlex, {},
                [h(NAvatar, {
                    src: row.goods_cover,
                    width: 30,
                    fallbackSrc: default_image,
                })]
            )

        },
    },

    {
    title: '商品',
    key: 'goods_name',
    width: 200,
    align: 'center',
    ellipsis: { tooltip: true },
  },{
    title: '规格',
    key: 'sku_name',
    width: 200,
    align: 'center',
    ellipsis: { tooltip: true },
  },
{
    title: '金额',
    key: 'price',
    width: 100,
    align: 'center',
    ellipsis: { tooltip: true },

  },

  {
    title: '加购时间',
    key: 'created_at',
    width: '100',
    align: 'center',
    ellipsis: { tooltip: true },
  },


  {
    title: '操作',
    key: 'actions',
    width: 100,
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        h(
            NPopconfirm,
            {
              onPositiveClick: () => handleDelete({ data_id: row.id }, false),
              onNegativeClick: () => {},
            },
            {
              trigger: () =>
                  withDirectives(
                      h(
                          NButton,
                          {
                            size: 'small',
                            type: 'error',
                          },
                          {
                            default: () => '移出购物车',
                            icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                          }
                      ),
                      [[vPermission, 'delete/api/content/category/delete']]
                  ),
              default: () => h('div', {}, '确定删除该数据吗?'),
            }
        ),
      ]
    },
  },
]



function formatTimestamp(timestamp) {
  const date = new Date(timestamp)
  const pad = (num) => num.toString().padStart(2, '0')
  const year = date.getFullYear()
  const month = pad(date.getMonth() + 1) // 月份从0开始，所以需要+1
  const day = pad(date.getDate())
  const hours = pad(date.getHours())
  const minutes = pad(date.getMinutes())
  const seconds = pad(date.getSeconds())
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
const datetimeRange = ref()
const handleDateRangeChange = (value) => {
  queryItems.value.start_time = formatTimestamp(value[0])
  queryItems.value.end_time = formatTimestamp(value[1])
}
async function  on_excel(){
   await api.onAppointmentExcel({start_time:queryItems.value.start_time,end_time:queryItems.value.end_time})
   data.show_excel = true
   //$message?.success('正在生成下载文件,请前往下载中心查看')
}
function go_excel(){
  router.push({ path: '/downloads/list' });
}
</script>

<template>
  <!-- 业务页面 -->
  <CommonPage show-footer title="购物车列表">
    <template #action>
      <div>

      </div>
    </template>
    <!-- 表格 -->
    <CrudTable
        ref="$table"
        v-model:query-items="queryItems"
        :columns="columns"
        :get-data="api.getOrdersCar"
        :scroll-x="1600"
    >
      <template #queryBar>
        <QueryBarItem label="客户姓名" :label-width="80">
          <NInput
              v-model:value="queryItems.user_name"
              clearable
              type="text"
              placeholder="请输入客户姓名"
              @keypress.enter="$table?.handleSearch()"
          />
        </QueryBarItem>
        <QueryBarItem label="商品名称" :label-width="80">
          <NInput
              v-model:value="queryItems.goods_name"
              clearable
              type="text"
              placeholder="请输入商品名称"
              @keypress.enter="$table?.handleSearch()"
          />
        </QueryBarItem>
      </template>
    </CrudTable>
  </CommonPage>
</template>
